using System.Linq;
using System.IO;
using mebc2.reflection;

namespace mebc2.viewer
{
    public static class ToDot_extension
    {
        public static string ToDot(this MetaData metadata)
        {
            var dotSource = new StringWriter();

            dotSource.WriteLine("digraph g {");
            if (metadata.IsBoard) WriteBoard(metadata, dotSource);
            dotSource.WriteLine("}");

            return dotSource.ToString();
        }


        private static void WriteBoard(MetaData metadata, StringWriter dotSource)
        {
            foreach (var inputPin in metadata.Wires.Where(w => w.Kind == WireKinds.Input))
                dotSource.WriteLine("{0};", NormalizeName(inputPin.To.Name));

            foreach (var wire in metadata.Wires.Where(w => w.Kind == WireKinds.Flow))
                dotSource.WriteLine("{0} -> {1};", NormalizeName(wire.From.Name), NormalizeName(wire.To.Name));

            foreach (var outputPin in metadata.Wires.Where(w => w.Kind == WireKinds.Output))
                dotSource.WriteLine("{0};", NormalizeName(outputPin.From.Name));
        }

        private static string NormalizeName(string name)
        {
            return name.Replace("+", ".").Split('.').Last();
        }
    }
}